import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import Cookies from 'js-cookie'
import Vue from 'vue'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/dashboard'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  
  NProgress.start()
  // try {
  //   // console.log('portal from:' + JSON.stringify(from))
  //   // console.log('portal to:' + JSON.stringify(to))
  // } catch (e) {
  //   console.log(e)
  // }

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  // debugger
  try {
    
    const Authorization = to.query.Authorization || Cookies.get('Authorization')
    const sysCode = to.query.sysCode || Cookies.get('sysCode')

    if (Authorization && Authorization !== '') {
      localStorage.setItem('Authorization', Authorization)
      // Cookies.set('Authorization', Authorization, { sameSite: 'None', secure: true })
    }
    if (sysCode && sysCode !== '' && sysCode !== 'undefined') {
      // Cookies.set('sysCode', sysCode, { sameSite: 'None', secure: true })
      localStorage.setItem('sysCode', sysCode)
    }
  } catch (e) {
    console.log("setcookis:"+e)
  }

  try{
    await Vue.prototype.loginUser()
  }catch(e){
    console.log("login:" + e)
  }

  if (hasToken) {
    next(`/dashboard?redirect=${to.path}`)
    NProgress.done()
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      // console.log('white list else')
      next(`/dashboard?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
